import { User } from '../models/User';

export default defineEventHandler(async (event) => {
    const method = event.method;
    const query = getQuery(event);
    const userId = query.userId as string;
    switch (method) {
        case 'GET':{
            try {
                const users = await User.find().select('-password');
                return { 
                    statusCode: 0,
                    data: users,
                    message: '获取用户列表成功'
                };
            } catch (error) {
                throw createError({
                    statusCode: 500,
                    message: '获取用户列表失败',
                    data: null
                });
            }
        }
        case 'POST':{
            try {
                const body = await readBody(event);
                const { username, email, password, age, phone, address } = body;
                // 验证必填字段
                if (!username || !email) {
                    throw createError({
                        statusCode: 400,
                        message: '用户名、密码不能为空',
                    });
                }
                const user = new User({ username, email, password, age, phone, address });
                
                const result = await user.save().catch((error: any) => {
                    // 检查是否是重复键错误
                    if (error.code === 11000) {
                        const field = Object.keys(error.keyPattern)[0];
                        return {
                            errorField: field
                        }
                    }
                    throw error;
                });
                if ('errorField' in result) {
                    switch(result.errorField){  
                        case 'username':
                            return {
                                statusCode: 10001,
                                message: '用户名已被使用',
                                data: null
                                };
                        case 'email':
                            return {
                                statusCode: 10002,
                                message: '邮箱已被使用',
                                data: null
                            };
                        case 'phone':
                            return {
                                statusCode: 10003,
                                message: '手机号已被使用',
                                data: null
                            };
                        default:
                            return {
                                statusCode: 10004,
                                message: '创建用户失败',
                                data: null
                            };  
                    }
                }
                return {
                    statusCode: 0,
                    message: '用户创建成功',
                    data: user.toJSON(),
                };
            } catch (error: any) {
                throw createError({
                    statusCode: error.statusCode || 500,
                    message: error.message || '创建用户失败',
                    data: null
                });
            }
        }
        case 'PUT': {
            try {
                if (!userId) {
                    throw createError({
                        statusCode: 400,
                        message: '用户ID是必填项',
                        data: null
                    });
                }
                
                const body = await readBody(event);
                const { username, email, password, age, phone, address, avatar, systemRole, status } = body;
                
                // 查找用户
                const user = await User.findOne({
                    $or: [
                        { _id: userId },
                        { userId: userId }
                    ]
                });
                
                if (!user) {
                    throw createError({
                        statusCode: 404,
                        message: '用户不存在',
                        data: null
                    });
                }
                
                // 构建更新对象
                const updateData: any = {};
                
                if (username !== undefined) updateData.username = username;
                if (email !== undefined) updateData.email = email;
                if (password !== undefined) {
                    // 如果提供了新密码，需要加密
                    updateData.password = password;
                }
                if (age !== undefined) updateData.age = age;
                if (phone !== undefined) updateData.phone = phone;
                if (address !== undefined) updateData.address = address;
                if (avatar !== undefined) updateData.avatar = avatar;
                if (systemRole !== undefined) updateData.systemRole = systemRole;
                if (status !== undefined) updateData.status = status;
                
                // 检查唯一性约束（排除当前用户）
                if (username && username !== user.username) {
                    const existingUser = await User.findOne({ username, _id: { $ne: user._id } });
                    if (existingUser) {
                        throw createError({
                            statusCode: 400,
                            message: '用户名已被使用',
                            data: null
                        });
                    }
                }
                
                if (email && email !== user.email) {
                    const existingUser = await User.findOne({ email, _id: { $ne: user._id } });
                    if (existingUser) {
                        throw createError({
                            statusCode: 400,
                            message: '邮箱已被使用',
                            data: null
                        });
                    }
                }
                
                if (phone && phone !== user.phone) {
                    const existingUser = await User.findOne({ phone, _id: { $ne: user._id } });
                    if (existingUser) {
                        throw createError({
                            statusCode: 400,
                            message: '手机号已被使用',
                            data: null
                        });
                    }
                }
                
                // 更新用户
                Object.assign(user, updateData);
                const updatedUser = await user.save();
                
                return {
                    statusCode: 0,
                    message: '用户更新成功',
                    data: updatedUser.toJSON(),
                };
            } catch (error: any) {
                throw createError({
                    statusCode: error.statusCode || 500,
                    message: error.message || '更新用户失败',
                    data: null
                });
            }
        }
        case 'DELETE': {
            try {
                if (!userId) {
                    throw createError({
                        statusCode: 400,
                        message: '用户ID是必填项',
                        data: null
                    });
                }
                
                // 查找用户
                const user = await User.findOne({
                    $or: [
                        { _id: userId },
                        { userId: userId }
                    ]
                });
                
                if (!user) {
                    throw createError({
                        statusCode: 404,
                        message: '用户不存在',
                        data: null
                    });
                }
                
                // 删除用户
                await User.deleteOne({ _id: user._id });
                
                return {
                    statusCode: 0,
                    message: '用户删除成功',
                    data: null
                };
            } catch (error: any) {
                throw createError({
                    statusCode: error.statusCode || 500,
                    message: error.message || '删除用户失败',
                    data: null
                });
            }
        }
    }
}); 